package com.matuw.android.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileIOUtils {
    private static final int BUFFER_SIZE = 524288;

    /**
     * Write file from input stream.
     */
    public static boolean writeFile(File file, InputStream is) {
        return writeFile(file, is, false);
    }


    /**
     * Write file from input stream.
     *
     * @param file   The file.
     * @param is     The input stream.
     * @param append True to append, false otherwise.
     * @return {@code true}: success<br>{@code false}: fail
     */
    public static boolean writeFile(File file, InputStream is, boolean append) {
        if (is == null || !FileUtils.createOrExistsFile(file)) {
            return false;
        }
        try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file, append), BUFFER_SIZE)) {
            byte[] buffer = new byte[BUFFER_SIZE];

            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }

            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
